<?php
/**
 * 微信小程序登陆
 */

namespace app\weapp\module\user;

use app\common\InstanceTrait;
use app\common\Redis;
use app\weapp\User\module\user\LoginByTelContext;
use function config;
use const app\weapp\User\module\user\_MSG_INVALID_CLIENT_PARAM;
use const app\weapp\User\module\user\_MSG_SYSTEM_SUCCESS;
use const app\weapp\User\module\user\_MSG_UNDEFINED_PARAM;
use const app\weapp\User\module\user\_TEL_CODE_LOGIN_NUMBER;

class Login
{
    use InstanceTrait;

    public function loginByWeapp($post, $sys)
    {
        if (empty($post["tel"])) {
            return array(_MSG_UNDEFINED_PARAM, "请填写手机号", ["tel" => "请填写手机号"]);
        }
        if (!isset($post["code"])) {
            return array(_MSG_UNDEFINED_PARAM, "手机验证码必填", ["code" => "手机验证码必填"]);
        }

        $codeTemp = Redis::getInstance()->redisGet($sys . '_' . _TEL_CODE_LOGIN_NUMBER . $post["tel"]);
        if ((config("app_env") == "local" || config("app_env") == "test" || config("app_env") == "pre") && $post["code"] == '1234') {
            $codeTemp["data"] = [];
            $codeTemp["data"]["code"] = '1234';
            $codeTemp["data"]["stamp"] = time();
            $codeTemp["code"] = 2000;
        }

        if (config("app_env") == "prod" && in_array($post['tel'], ['18888888888', '18888888887', '18888888886', '18888888885', '18888888884', '18888888889']) && $post['code'] == '9218') {
            $codeTemp["data"] = [];
            $codeTemp["data"]["code"] = '9218';
            $codeTemp["data"]["stamp"] = time();
            $codeTemp["code"] = 2000;
        }

        if ($codeTemp["code"] == _MSG_SYSTEM_SUCCESS) {
            $blank = (int)time() - (int)$codeTemp["data"]["stamp"];
            if ($blank > 12 * 60) {  // 验证码失效
                return array(_MSG_INVALID_CLIENT_PARAM, "验证码失效", ["code" => "验证码失效"]);
            }

            if ($codeTemp["data"]["code"] != $post["code"]) {
                return array(_MSG_INVALID_CLIENT_PARAM, "验证码错误", ["code" => "验证码错误"]);
            }
        } else {
            return array(_MSG_INVALID_CLIENT_PARAM, "验证码失效，请重新获取", ["code" => "验证码失效，请重新获取"]);
        }
        //登陆用户
        $loginByTelContext = new LoginByTelContext($post);
        $loginRes = $this->loginByTel($loginByTelContext, $sys);
        if ($loginRes[0] != _MSG_INVALID_CLIENT_PARAM) {
            return $loginRes;
        }
        //用户不存在注册用户
        $registerRes = $this->registerUser($post, $sys);
        return $registerRes;
    }

}
